<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatDate } from '@/utils'
import { batchAddEmployees } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results }) {
      console.log(results)
      const objKeyTo = {
        '入职日期': 'timeOfEntry',
        '姓名': 'username',
        '工号': 'workNumber',
        '手机号': 'mobile',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      this.tableData = results.map(item => {
        const resObj = {}
        for (const k in item) {
          if (k === '入职日期' || k === '转正日期') {
            resObj[objKeyTo[k]] = formatDate(item[k])
          } else {
            resObj[objKeyTo[k]] = item[k]
          }
        }
        return resObj
      })
      console.log(this.tableData)
      await batchAddEmployees(this.tableData)
      this.$message.success('导入成功')
      this.$router.back()
    }
  }
}
</script>
